﻿/* ********************************************************************************
 * 名称：Cpn_DomainService
 * 描述：企业资料表  领域服务接口实现类（本类通过CodeSmith软件生成生成）
 * 创建人：HFL
 * 创建日期：2020-06-01 17:48:55
 * 修改人：
 * 修改日期：
 * *******************************************************************************/
using WPay.Domain.Base;
using WPay.Domain.Model.DTOs;
using WPay.Domain.Model.Entities;
using WPay.Domain.MainModule.Interface.DomainServices;
using WPay.Domain.MainModule.Interface.RepositoryServices;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http;
using Model.DTOModel;
using Newtonsoft.Json;
using Utility;
using Utility.Enums;
using System.Linq;
using WPay.Infrastructure.Unity;
using CommonUtility;
using Amazon.DynamoDBv2.Model;
using System.Data.Entity;
using WPay.Infrastructure.EFCore;
using System.Text.RegularExpressions;
using System.Dynamic;
using WPay.Infrastructure.Unity.Enums;
using WPay.Infrastructure.Common;
using Aop.Api;
using Aop.Api.Request;
using Aop.Api.Response;
using WPay.Domain.Model.DTOs.Parms;
using WPay.Infrastructure.Repository.MainModule;
using WPay.Domain.Model.DTOs.Lamada;
using System.IO;

namespace WPay.Domain.MainModule
{
    /// <summary>
    /// 企业资料表 领域服务接口实现类
    /// </summary>
    public class Cpn_DomainService : ICpn_DomainService
    {

        /// <summary>
        /// 企业资料表 领域服务接口
        /// </summary>
        private readonly ICpn_RepositoryService cpn_RepositoryService;
        private readonly IMngrLog_DomainService _mngrLog_DomainService;
        private readonly IEfCore_RepositoryService _efCore_RepositoryService;
      
        private Entities db;
  

        /// <summary>
        /// 带参构造，用于IOC
        /// </summary>
        public Cpn_DomainService(ICpn_RepositoryService _cpn_RepositoryService, IEfCore_RepositoryService efCore_RepositoryService,
            IMngrLog_DomainService mngrLog_DomainService
            )
        {
            cpn_RepositoryService = _cpn_RepositoryService;
            _efCore_RepositoryService = efCore_RepositoryService;
            _mngrLog_DomainService = mngrLog_DomainService;
         
            db = _efCore_RepositoryService.DbContext();
        }


        #region 由软件生成，禁止修改，若需要扩展，请在下方进行扩展

        /// <summary>
        /// 根据主键获取企业资料表资料信息
        /// </summary>
        /// <param name="_cpnID">企业代码</param>
        /// <returns>返回单个企业资料表数据实体</returns>
        public Cpn Get(string _cpnID)
        {
            return this.cpn_RepositoryService.Get(_cpnID);
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_cpnID">企业代码</param>
        /// <returns>返回企业资料表数据集合</returns>
        public List<Cpn> GetAll(string _cpnID)
        {
            return this.cpn_RepositoryService.GetAll(_cpnID);
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <returns>返回企业资料表数据集合</returns>
        public List<Cpn> GetAll(Hashtable _param)
        {
            return this.cpn_RepositoryService.GetAll(_param);
        }

        /// <summary>
        /// 按照分页条件查询数据集
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <param name="_pageIndex">查询页码，从1开始，必传</param>
        /// <param name="_pageSize">每页查询数据条数，必传</param>
        /// <param name="_sort">排序列名，若要降序请用列名+" DESC"，必传</param>
        /// <param name="_pageCount">返回总页码数</param>
        /// <param name="_dataCount">返回总数据条数</param>
        /// <returns>返回企业资料表数据集合</returns>
        public List<Cpn> GetByPage(Hashtable _param, int _pageIndex, int _pageSize, string _sort, out int _pageCount, out int _dataCount)
        {
            return this.cpn_RepositoryService.GetByPage(_param, _pageIndex, _pageSize, _sort, out _pageCount, out _dataCount);
        }

        /// <summary>
        /// 插入企业资料表数据
        /// </summary>
        /// <param name="_cpn">需要插入的企业资料表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(Cpn _cpn)
        {
            return this.cpn_RepositoryService.Add(_cpn);
        }

        /// <summary>
        /// 批量插入企业资料表数据
        /// </summary>
        /// <param name="_cpnList">需要插入的企业资料表数据集合</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(List<Cpn> _cpnList)
        {
            return this.cpn_RepositoryService.Add(_cpnList);
        }

        /// <summary>
        /// 根据主键更新企业资料表数据
        /// </summary>
        /// <param name="_cpn">需要更新的企业资料表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(Cpn _cpn)
        {
            return this.cpn_RepositoryService.Update(_cpn);
        }

        /// <summary>
        /// 根据主键更新企业资料表指定字段
        /// </summary>
        /// <param name="_cpn">需要更新的企业资料表数据实体</param>
        /// <param name="_updateProNames">需要更新的字段名</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(Cpn _cpn, params string[] _updateProNames)
        {
            return this.cpn_RepositoryService.Update(_cpn, _updateProNames);
        }


        #endregion

        /*业务扩展代码*/
        #region 业务扩展代码
        /// <summary>
        /// 保存企业账户支付配置信息
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="LoginName"></param>
        /// <returns></returns>
     

    
       

       
       
       

      

        /// <summary>
        /// 添加企业基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="httpRequest"></param>
        /// <returns></returns>
        public void SaveCpnNormal(Cpn model, HttpRequest httpRequest)
        {

            dynamic result = new ExpandoObject();
            var regtel = "^1[0-9]{10}$";
            var regemal = @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";
            var zznumber = @"^1\d{10}$";
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    var tableData = httpRequest.Form["tableData"];
                    model.Stt = 0;
                    model.OpnDt = DateTime.Now;
                    model.UptDtt = DateTime.Now;

                    #region 服务端数据验证
                    if (string.IsNullOrEmpty(model.ERPCpnId))
                    {
                        throw new UNException("ERP代码不能为空");
                    }
                    if (new Regex(zznumber).IsMatch(model.CpnID))
                    {
                        throw new UNException("商户编号格式不正确");
                    }
                    if (string.IsNullOrEmpty(model.Name))
                    {
                        throw new UNException("商户名称不能为空");
                    }
                    if (!string.IsNullOrEmpty(model.Tel) && !new Regex(regtel).IsMatch(model.Tel))
                    {
                        throw new UNException("办公电话格式不正确");
                    }
                    if (!string.IsNullOrEmpty(model.LnkPhn) && !new Regex(regtel).IsMatch(model.LnkPhn))
                    {
                        throw new UNException("联系人电话格式不正确");
                    }
                    if (!string.IsNullOrEmpty(model.LnkEml))
                    {
                        var emils = model.LnkEml.Split(",").ToList();
                        emils.ForEach(a =>
                        {
                            if (!new Regex(regemal).IsMatch(a))
                            {
                                throw new UNException("联系人邮箱格式不正确");
                            }
                        });
                    }
                    if (!string.IsNullOrEmpty(model.CfoPhn) && !new Regex(regtel).IsMatch(model.CfoPhn))
                    {
                        throw new UNException("财务联系电话格式不正确");
                    }
                    if (!string.IsNullOrEmpty(model.CfoEml) && !new Regex(regemal).IsMatch(model.CfoEml))
                    {
                        throw new UNException("财务邮箱格式不正确");
                    }
                    if (!string.IsNullOrEmpty(model.CioPhn) && !new Regex(regtel).IsMatch(model.CioPhn))
                    {
                        throw new UNException("系统管理员格式不正确");
                    }
                    if (string.IsNullOrEmpty(model.CpnID))
                    {
                        if (_efCore_RepositoryService.Exists<Cpn>(new DirectSpecification<Cpn>(a => a.ERPCpnId == model.ERPCpnId)))
                        {
                            throw new UNException("ERP企业代码重复,请检查");
                        }
                        if (_efCore_RepositoryService.Exists<Cpn>(new DirectSpecification<Cpn>(a => a.Name == model.Name)))
                        {
                            throw new UNException("商户简称重复");
                        }

                    }
                    else
                    {
                        if (_efCore_RepositoryService.Exists<Cpn>(new DirectSpecification<Cpn>(a => a.ERPCpnId == model.ERPCpnId && a.CpnID != model.CpnID)))
                        {
                            throw new UNException("ERP企业代码重复,请检查");
                        }
                        if (_efCore_RepositoryService.Exists<Cpn>(new DirectSpecification<Cpn>(a => a.Name == model.Name && a.CpnID != model.CpnID)))
                        {
                            throw new UNException("商户简称重复");
                        }

                    }
                    #endregion

                    if (!string.IsNullOrEmpty(model.CpnID))
                    {
                        var cpndb = db.Cpn.Find(model.CpnID);
                        var oldjson = JsonConvert.SerializeObject(cpndb);
                        cpndb.Name = model.Name;
                        cpndb.CpnItTp = model.CpnItTp;
                        cpndb.City = model.City;
                        cpndb.Adr = model.Adr;
                        cpndb.Tel = model.Tel;
                        cpndb.Fax = model.Fax;
                        cpndb.OpnBnk = model.OpnBnk;
                        cpndb.ActNo = model.ActNo;
                        cpndb.TaxID = model.TaxID;
                        cpndb.Lnkr = model.Lnkr;
                        cpndb.LnkPhn = model.LnkPhn;
                        cpndb.LnkEml = model.LnkEml;
                        cpndb.Cfo = model.Cfo;
                        cpndb.CfoPhn = model.CfoPhn;
                        cpndb.CfoEml = model.CfoEml;
                        cpndb.Cio = model.Cio;
                        cpndb.CioPhn = model.CioPhn;
                        cpndb.CioEml = model.CioEml;
                        cpndb.Customer = model.Customer;
                        cpndb.Brf = model.Brf;
                        cpndb.Uptr = model.Uptr;
                        cpndb.ERPCpnId = model.ERPCpnId;
                        cpndb.Deskey = model.Deskey;
                        cpndb.IsCheckMony = model.IsCheckMony;
                        cpndb.CheckMonyMax = model.CheckMonyMax;
                        cpndb.RootMsgAPI = model.RootMsgAPI;
                        _efCore_RepositoryService.Update(cpndb, x => x.Name, x => x.CpnItTp, x => x.City, x => x.Adr, x => x.Tel, x => x.Fax, x => x.OpnBnk, x => x.ActNo, x => x.TaxID,
                        x => x.Lnkr, x => x.LnkPhn, x => x.LnkEml, x => x.Cfo, x => x.CfoPhn, x => x.CfoEml, x => x.CfoEml, x => x.Cio, x => x.CioPhn
                        , x => x.CioEml, x => x.Customer, x => x.Brf, x => x.Uptr, x => x.ERPCpnId, x => x.Deskey,
                        x => x.IsCheckMony, x => x.CheckMonyMax, x => x.RootMsgAPI
                        );
                        _mngrLog_DomainService.AddMngrLog("修改企业信息", $"修改前{oldjson}，修改后{JsonConvert.SerializeObject(cpndb)}");
                        db.Entry(cpndb).State = Microsoft.EntityFrameworkCore.EntityState.Detached;
                    }
                    else
                    {
                        model.CpnID = cpn_RepositoryService.GetMaxCpnId();
                        model.OpnDt = DateTime.Now;
                        model.MhNo = DateTime.Now.ToString("yyyyMMdd") + model.CpnID;
                        model.ApLyTyp = 1;
                        model.BllNo = BllNoHelper.CreateBillNo(model.CpnID, BllTyp.CpnInfo);
                        _mngrLog_DomainService.AddMngrLog("添加企业", $"{model.Name} 企业被添加");
                        _efCore_RepositoryService.Add(model);
                    }
                    #region 门店处理
                    List<CpnOrg> orgLst = new List<CpnOrg>();
                    if (!string.IsNullOrEmpty(tableData))
                    {
                        var orglist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(tableData);

                        foreach (Dictionary<string, string> item in orglist)
                        {
                            var OrgID = item["机构代码"].ToString();
                            var Name = item["名称"].ToString();
                            var pid = "";
                            var typ = "";
                            var Brf = "";
                            if (item.ContainsKey("备注"))
                            {
                                Brf = item["备注"].ToString();
                            }
                            if (item.ContainsKey("上级编号"))
                            {
                                pid = item["上级编号"].ToString();
                            }
                            if (item.ContainsKey("类型"))
                            {
                                typ = item["类型"].ToString();
                            }
                            orgLst.Add(new CpnOrg()
                            {
                                CpnID = model.CpnID,
                                OrgID = OrgID,
                                Name = Name,
                                Brf = Brf,
                                UptDtt = DateTime.Now
                            });
                        }
                        var orgids = orgLst.Select(x => x.OrgID);
                        var orgLstgrop = orgLst.GroupBy(x => x.OrgID).ToList();
                        orgLstgrop.ForEach(x =>
                        {
                            if (x.Count() > 1)
                            {
                                throw new UNException($"上传的门店中包含重复门店{x.Key},请重新上传");
                            }
                        });
                        var dblist = _efCore_RepositoryService.GetMany<CpnOrg>(new DirectSpecification<CpnOrg>(x => x.CpnID == model.CpnID && orgids.Contains(x.OrgID)));
                        if (dblist.Count() > 0)
                        {
                            throw new UNException($"上传的门店中包含已导入门店{string.Join(",", dblist.Select(x => x.OrgID))},请重新上传");
                        }
                        if (orgLst != null && orgLst.Count > 0)
                        {
                            _efCore_RepositoryService.AddBatch<CpnOrg>(orgLst);
                        }
                    }
                    #endregion
                    //若当前企业没有任何门店,则默认新增总部
                    if (!_efCore_RepositoryService.Exists<CpnOrg>(new DirectSpecification<CpnOrg>(x => x.CpnID == model.CpnID)) && !orgLst.Exists(x => x.OrgID == "0000"))
                    {
                        _efCore_RepositoryService.Add<CpnOrg>(new CpnOrg()
                        {
                            CpnID = model.CpnID,
                            OrgID = "0000",
                            Name = "总部",
                            Brf = "系统默认生成",
                            UptDtt = DateTime.Now,
                        });
                    }
                    result.Success = true;
                    result.Message = "添加成功!";
                    //更新邮件时间
                    if (!string.IsNullOrEmpty(model.CioEml))
                    {
                        try
                        {

                            var cpnid = model.CpnID;
                            var title = $"[{model.Name}]定时对账";
                            var time = model.CioEml;
                            var res = HttpHelper.HttpGetString($"http://rd5-wpc-wpaywebserviesui.wuerp.com/TaskBackGround/add?taskName={cpnid}-{title}&groupName={cpnid}-{title}&interval=0+0+{time}+*+*+%3F+&apiUrl=http:%2F%2Frd5-wpc-wpaywebserviesapi.wuerp.com%2Fapi%2Fv1.0%2Fservice%2FRedisRCToCpn%3Fcpnid%3D{cpnid}&authKey=&authValue=&describe={cpnid}-{title}&requestType=get");
                            var resdic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
                            LoggerHelper.Log($"对账任务add：{res}");
                            if (resdic.ContainsKey("status") && resdic["status"] == "false")
                            {
                                var resupdate = HttpHelper.HttpGetString($"http://rd5-wpc-wpaywebserviesui.wuerp.com/TaskBackGround/update?taskName={cpnid}-{title}&groupName={cpnid}-{title}&interval=0+0+{time}+*+*+%3F+&apiUrl=http:%2F%2Frd5-wpc-wpaywebserviesapi.wuerp.com%2Fapi%2Fv1.0%2Fservice%2FRedisRCToCpn%3Fcpnid%3D{cpnid}&authKey=&authValue=&describe={cpnid}-{title}&requestType=get&status=0&cellClassName=%7B%22operat%22:%22view-log%22%7D");
                                LoggerHelper.Log($"对账任务update：{res}");
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                    _efCore_RepositoryService.SaveChanges();
                    tran.Commit();

                }
                catch (Exception e)
                {
                    tran.Rollback();
                    throw e;
                }
            }

        }
       
       
      
        /// <summary>
        /// 删除Cpn
        /// </summary>
        /// <param name="deld"></param>
        /// <returns></returns>
        public IEnumerable<string> DelCpn(HttpRequest httpRequest)
        {
            IEnumerable<string> deld = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(httpRequest.Form["delds"]);
            _efCore_RepositoryService.LogicDelete(new DirectSpecification<Cpn>(y => deld.Contains(y.CpnID)));
            var names = (_efCore_RepositoryService.GetMany(new DirectSpecification<Cpn>(y => deld.Contains(y.CpnID)))
                     ).Select(x => x.CpnID);
            _mngrLog_DomainService.AddMngrLog("删除支付账户", $"{string.Join(",", names)}支付账户被删除");
            _efCore_RepositoryService.SaveChanges();
            return names;
        }
     
        #endregion
    }
}
